package com.maxmlr.base.proxy;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @ClassName ProxyTest
 * @Description TODO
 * @Author maxiao
 * @Date 2020/3/6 上午11:07
 * @Version V1.0
 */
public class ProxyTest {

    public static void main(String[] args) throws Exception {
        UserService userService = new UserServiceImpl();

        Object obj = Proxy.newProxyInstance(
                userService.getClass().getClassLoader(),
                userService.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Object o = method.invoke(userService, args);
                        return o;
                    }
                });

        UserService userProxy = (UserService) obj;

        String userName = userProxy.getUserName(1);

        Class<?> aClass = Class.forName("com.maxmlr.base.proxy.TestController");
        Object instance = aClass.newInstance();
        Field field = aClass.getDeclaredField("userService");
        field.setAccessible(true);
        //注入代理对象
        field.set(instance, obj);
        TestController testController = (TestController) instance;
        testController.test(2);

        System.out.println(userName);
    }
}
